import os
from flask import Blueprint, send_from_directory, current_app, render_template, jsonify, abort, send_file, request
from ..api.auth import login_required
from ..utils.file_utils import get_file_size, get_file_type, get_mime_type, can_preview
from ..api.system import record_download
import json

download_bp = Blueprint('download', __name__)

@download_bp.route('/')
@login_required
def index():
    """显示文件列表页面"""
    files = []
    info_file = os.path.join(current_app.config['UPLOAD_FOLDER'], 'file_info.json')
    
    if os.path.exists(info_file):
        try:
            with open(info_file, 'r', encoding='utf-8') as f:
                files = json.load(f)
                # 确保size字段是数字
                for file in files:
                    if isinstance(file['size'], str):
                        try:
                            # 尝试将字符串转换为数字
                            file['size'] = float(file['size'].split()[0]) * 1024  # 假设单位是KB
                        except (ValueError, IndexError):
                            # 如果转换失败，获取实际文件大小
                            try:
                                file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], file['filename'])
                                file['size'] = os.path.getsize(file_path)
                            except OSError:
                                file['size'] = 0
                    
                    # 确保文件类型信息
                    if 'file_type' not in file:
                        file['file_type'] = get_file_type(file['filename'])
                        
                    # 添加支持预览的标志
                    file['can_preview'] = can_preview(file['filename'])
        except (json.JSONDecodeError, FileNotFoundError):
            files = []
    
    return render_template('files.html', files=files)

@download_bp.route('/download/<filename>')
@login_required
def download_file(filename):
    """下载文件"""
    file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
    if not os.path.exists(file_path):
        abort(404)
    
    # 记录下载事件
    ip = request.remote_addr
    record_download(filename, ip)
        
    mime_type = get_mime_type(filename)
    return send_file(
        file_path,
        mimetype=mime_type,
        as_attachment=True,
        download_name=filename
    )

@download_bp.route('/preview/<filename>')
@login_required
def preview_file(filename):
    """预览文件内容"""
    file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
    if not os.path.exists(file_path):
        abort(404)
        
    if not can_preview(filename):
        abort(400)  # 不支持预览的文件类型
        
    mime_type = get_mime_type(filename)
    return send_file(
        file_path,
        mimetype=mime_type,
        as_attachment=False
    )

@download_bp.route('/api/documents')
@login_required
def list_documents():
    files = []
    upload_dir = current_app.config['UPLOAD_FOLDER']
    
    for filename in os.listdir(upload_dir):
        file_path = os.path.join(upload_dir, filename)
        if os.path.isfile(file_path) and not filename.endswith('.json'):
            file_type = get_file_type(filename)
            files.append({
                'filename': filename,
                'size': get_file_size(file_path),
                'download_url': f'/documents/download/{filename}',
                'file_type': file_type,
                'can_preview': can_preview(filename)
            })
            
    return jsonify({'documents': files})

@download_bp.route('/search')
@login_required
def search_files():
    """搜索文件"""
    query = request.args.get('q', '').lower()
    files = []
    info_file = os.path.join(current_app.config['UPLOAD_FOLDER'], 'file_info.json')
    
    if os.path.exists(info_file):
        try:
            with open(info_file, 'r', encoding='utf-8') as f:
                all_files = json.load(f)
                # 搜索文件名和上传时间
                files = [file for file in all_files if 
                        query in file['original_name'].lower() or 
                        query in file['upload_time'].lower() or
                        query in file['uploader_location'].lower()]
        except (json.JSONDecodeError, FileNotFoundError):
            files = []
    
    return jsonify({'files': files}) 